package com.yonyou.pmclouds.basecom.bp.template;

import com.yonyou.pmclouds.basecom.dao.BaseMapper;
import com.yonyou.pmclouds.basecom.entity.Entity;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.ConcurrentOperationException;
import com.yonyou.pmclouds.basecom.exception.DataModifiedException;
import com.yonyou.pmclouds.basecom.lock.AutoReleaseLockUtil;
import com.yonyou.pmclouds.basecom.util.BeanHelper;
import com.yonyou.pmclouds.basecom.util.ChangeFlagCheckUtil;
import com.yonyou.pmclouds.basecom.util.CommonFieldConst;

public class SingleDeleteBpTemplate<T extends Entity> extends SingleOperateBpTemplate<T> {
    private static final String[] DR_FIELDS = new String[]{CommonFieldConst.DR};
    private BaseMapper<T> mapper;

    public SingleDeleteBpTemplate(BaseMapper<T> mapper) {
        this.mapper = mapper;
    }

    @Override
    protected T getOrigVO(T vo) throws BusinessException {
        Object pk = vo.pkFiledValue();
        if (pk == null) {
            return null;
        }
        // lock
        if (!AutoReleaseLockUtil.addAutoReleaseLock(pk.toString())) {
            throw new ConcurrentOperationException();
        }
        // get&check
        T orig = mapper.getById(vo.pkFiledValue());
        if (!ChangeFlagCheckUtil.isSameFlag(vo, orig)) {
            throw new DataModifiedException();
        }
        return orig;
    }

    @Override
    protected void operateDirect(T vo, T orig) {
        BeanHelper.setProperty(vo, CommonFieldConst.DR, (byte) 1);
        mapper.updateFields(vo, DR_FIELDS);
    }

    public T delete(T vo) throws BusinessException {
        return execute(vo);
    }
}
